package command;

import java.util.Vector;

public class Invoker {
	
	private ICommand command;
	
	private Vector<ICommand> commands;
	
	private int index = -1;
	
    private Invoker() {
    	commands = new Vector<ICommand>();
    }
    
    private static class InvokerHolder { 
    	public static final Invoker instance = new Invoker();
    }
    
    public static Invoker getInstance() {
    	return InvokerHolder.instance;
    }
    
    public void setCommand(ICommand command) {
    	this.command = command;
    }
    
    public void run() {
    	command.execute();
    }
    
    public void addCommand(ICommand command) {
    	index++;
    	if(!commands.isEmpty()) {
    		for(int i = (commands.size() - 1); i >= index; i--) {
    			commands.remove(i);
    		}
    		commands.trimToSize();
    	}
    	commands.add(command);
    }
    
    public void redo() {
    	if(index + 1 < commands.size()) {
    		index++;
    		commands.get(index).execute();
    	}
    }
    
    public void undo() {
    	if(index > -1) {
    		commands.get(index).undo();
    		index--;
    	}
    }
    
    public void reset() {
    	commands = new Vector<ICommand>();
    	index = -1;
    }
    
}